﻿using System;
using System.IO;
using System.Net;

namespace Cms.Utilities
{
    public class RemoteFileHandler
    {
        public static Stream GetFileFromUrl(string url)
        {
            var req = (HttpWebRequest)WebRequest.Create(url);
            req.Timeout = 4000;
            HttpWebResponse resp;
            try
            {
                resp = (HttpWebResponse)req.GetResponse();
                if (resp.StatusCode == HttpStatusCode.OK)
                    return resp.GetResponseStream();
            }
            catch (WebException ex)
            {
                if (ex.Status == WebExceptionStatus.ProtocolError)
                {
                    resp = ex.Response as HttpWebResponse;
                    if (resp != null)
                    {
                    }
                }
            }
            return null;
        }

        public static void SaveRemoteFileToDisk(string url, string savePath, bool overwrite)
        {
            try
            {
                Stream stream = GetFileFromUrl(url);
                if (File.Exists(savePath) && overwrite)
                    File.Delete(savePath);
                FileStream fs = File.Create(savePath);
                var buffer = new byte[32 * 1024]; // 32 KB
                int chunkSize;
                while ((chunkSize = stream.Read(buffer, 0, buffer.Length)) > 0)
                {
                    fs.Write(buffer, 0, chunkSize);
                }
                fs.Close();
                fs.Dispose();
            }
            catch (Exception ex)
            {
                Logging.LogError("SaveRemoteFileToDisk: " + ex.StackTrace + Environment.NewLine, ex);
                throw;
            }
        }
    }
}